package com.biter.service;

import com.biter.util.Util;

import android.R.integer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.util.Log;


public class BootReceiver extends BroadcastReceiver {
	
    private static final String TAG = "BootReceiver";
	@Override
	public void onReceive(Context context, Intent mintent) {
		String actionName = mintent.getAction();
		SharedPreferences setInfo = context.getSharedPreferences("setInfo", 0);
		int time = Integer.parseInt(setInfo.getString("TimeInterval", "20"));
		
		if (actionName.equals(Intent.ACTION_BOOT_COMPLETED)||actionName.equals("startPollService")){
			
			if(!Util.isServiceRunning(context, PollingService.ACTION)){
				Log.v(TAG, " start Polling Service when phone boot completed.");
			     PollingUtils.startPollingService(context, time, PollingService.class, PollingService.ACTION);
			}
			
		}else if(actionName.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
			Log.v(TAG, " mobile phone internet status changed.");
			boolean success = false;
			ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
			if (State.CONNECTED == state) { 
				success = true;
			} else {
				state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
				if(State.CONNECTED == state){
					success = true;
				}else{
					success = false;
				}
			}
			
			if(success){
				Log.v(actionName, " Internet is connected. ");
				if(!Util.isServiceRunning(context, PollingService.ACTION)){
					PollingUtils.startPollingService(context, time, PollingService.class, PollingService.ACTION);
				}
			}else{
				Log.v(actionName, " Internet is closed. ");
				PollingUtils.stopPollingService(context, PollingService.class, PollingService.ACTION);
			}
		}
	}
}
